<?php
//	MTSM - Minetest Server Manager - Server management frontend
//	(C) Chris Dorman, 2021
//	License: CC-BY-SA version 3.0
//	http://notabug.org/Pentium44/MTSM

session_start();
include "config.php";
include "functions.php";

// check if flatfile database location is populated
if(!file_exists("mtm_db"))
{
	mkdir("mtm_db", 0777);
    generateToken();
}

if(!file_exists("mtm_db/events"))
{
	mkdir("mtm_db/events", 0777);
}

if(!file_exists("mtm_db/worlds"))
{
	mkdir("mtm_db/worlds", 0777);
}

if(!file_exists("mtm_db/pids"))
{
	mkdir("mtm_db/pids", 0777);
}

if(!file_exists("mtm_db/users"))
{
	mkdir("mtm_db/users", 0777);
}

// Adding a usermods directory
if(!file_exists("mtm_db/usermods")) 
{
    mkdir("mtm_db/usermods");
}

if(!file_exists("mtm_db/users/usercount"))
{
	file_put_contents("mtm_db/users/usercount", "0");
}

$username = $_SESSION['mtm-user'];

?>
<!DOCTYPE html>
<html lang="en-us">
<head>
<title><?php echo $mtsmtitle; ?></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=.55, shrink-to-fit=yes"><meta name="description" content="<?php echo htmlentities($mtsmtitle) . " - " . $desc; ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="ctn/style.css">
</head>
<body>

<div class="maincontain">
<div id="navcontainer">
        <div id="navbar"><!--
        <?php if(isset($_SESSION['mtm-user']) && isset($_SESSION['mtm-pass'])) { 
                  if($username == "admin") {?>
        --><a href="index.php">Manage</a><!--
        --><a href="?do=about">About</a><!--
        --><a href="?do=logout">Logout</a><!--
        <?php     } else { ?>
	    --><a href="index.php">Create</a><!--
        --><a href="?do=manage">Manage</a><!--
        --><a href="?do=about">About</a><!--
        --><a href="?do=logout">Logout</a><!--
	    <?php     }
              } else {  ?>
        --><a href="?forms=login">Login</a><!--
        --><a href="?forms=register">Register</a><!--
        --><a href="?do=about">About</a><!--
        <?php } ?>
        --></div>
</div>
<div class='title'><?php echo $mtsmtitle; ?></div>
<div class='contain'>

<?php

if(isset($_GET['forms']))
{
	$forms = $_GET['forms'];
	$id = $_GET['pid'];
	if($forms=="register") {
		registerForm();
	}
	else if($forms=="login") {
		loginForm();
	}
	else { echo "ERROR: Unknown form-name<br>"; }
}
else if(isset($_GET['notify']))
{
        $notify = $_GET['notify'];
        if($notify=="1") { echo "Error: User not found"; }
        else if($notify=="2") { echo "Error: Incorrect password provided"; }
        else if($notify=="3") { echo "Error: Please fill out all the text boxes"; }
        else if($notify=="4") { echo "Error: The provided passwords did not match"; }
        else if($notify=="5") { echo "Error: Special characters cannot be used in your username, and admin may not be used."; }
        else if($notify=="6") { echo "Error: This username is already in use"; }
        else { echo "Error: unknown error... this is quite unusual..."; }
}
else if(isset($_GET['do']))
{
	$do = $_GET['do'];
	// Server admin can just delete ssb_db
	/*if($do=="clean")
	{
		if($_POST['password']!="" && $_POST['password']==$pw)
		{
			$db_content = glob("ssb_db/" . '*', GLOB_MARK);
			foreach($db_content as $file)
			{
				unlink($file);
			}
			rmdir("mtm_db");
			echo "Database Cleaned<br>";
		}
		else
		{
			echo "ERROR: Wrong Password<br>";
		}
	}*/


	// grab session values and send friend request functions.
	
	if($do=="create-multicraft") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(!is_dir("mtm_db/worlds/$userid")) {
                mkdir("mtm_db/worlds/$userid");

                // Check if usermods folder exists, create if not!
                if(!is_dir("mtm_db/usermods/$username")) {
                    mkdir("mtm_db/usermods/$username");
                }

                // Lets setup a default configuration script
                $config_contents = "port = 30" . $userid . "\n";
                $config_contents .= "name = " . $username . "\n";
                $config_contents .= "max_users = $max_slot_count\n";
                $config_contents .= "default_game = minetest_game\n";
                $config_contents .= "default_privs = shout, interact\n";
                $config_contents .= "secure.trusted_mods = irc\n";
                $config_contents .= "server_address = $defaultip\n";
                $config_contents .= "irc.server = $default_irc_server\n";
                $config_contents .= "irc.port = $default_irc_port\n";
                $config_contents .= "irc.nick = MT" . $portrange . $userid . "\n";
                $config_contents .= "irc.channel = #$username\n";
                file_put_contents("mtm_db/worlds/$userid/minetest.conf", $config_contents);

                // Toggle server off, to the web panel
                file_put_contents("mtm_db/users/$userid.pid.statuscode", "false");
                file_put_contents("mtm_db/users/$userid.pid.status", "<div style='display:inline;color:#ff0000;'>Stopped</div>\n");

				// Trigger event to start server
				file_put_contents("mtm_db/events/$userid", "tar -xzf servers/multicraft.tgz -C mtm_db/worlds/$userid");
				file_put_contents("mtm_db/users/$userid.type", "multicraft");
				header("Location: index.php?do=manage");
			} else {
				echo "Error: World exists, please click &quot;Manage&quot; to start / stop your server, download a world backup, or delete your current world!";
			}
		}
	}
	
    // Create private server for testing or private party reasons.
	if($do=="create-minetest") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(!is_dir("mtm_db/worlds/$userid")) {
				mkdir("mtm_db/worlds/$userid");

                // Check if usermods folder exists, create if not!
                if(!is_dir("mtm_db/usermods/$username")) {
                    mkdir("mtm_db/usermods/$username");
                }

                // Lets setup a default configuration script
                $config_contents = "port = " . $portrange . $userid . "\n";
                $config_contents .= "name = " . $username . "\n";
                $config_contents .= "max_users = $max_slot_count\n";
                $config_contents .= "default_game = minetest_game\n";
                $config_contents .= "default_privs = shout, interact\n";
                $config_contents .= "secure.trusted_mods = irc\n";
                $config_contents .= "server_address = $defaultip\n";
                $config_contents .= "irc.server = $default_irc_server\n";
                $config_contents .= "irc.port = $default_irc_port\n";
                $config_contents .= "irc.nick = MT$portrange$userid\n";
                $config_contents .= "irc.channel = #$username\n";
                file_put_contents("mtm_db/worlds/$userid/minetest.conf", $config_contents);

                // Toggle server off, to the web panel
                file_put_contents("mtm_db/users/$userid.pid.statuscode", "false");
                file_put_contents("mtm_db/users/$userid.pid.status", "<div style='display:inline;color:#ff0000;'>Stopped</div>\n");

                // Trigger event to start servver
                file_put_contents("mtm_db/events/$userid", "tar -xzf servers/minetest-current.tgz -C mtm_db/worlds/$userid");
                file_put_contents("mtm_db/users/$userid.type", "minetest");
                header("Location: index.php?do=manage");
			} else {
				echo "Error: World exists, please click &quot;Manage&quot; to start / stop your server, download a world backup, or delete your current world!";
			}
		}
	}
	
    if($do=="configure-game") {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3,url=index.php?do=configure-mods' />";
                } else {
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
                    if($serverstatus == "false") {
                        if(isset($_GET['game']) && $_GET['game']!="" && is_dir("games/" . stripslashes($_GET['game']))) {
                            $gamename = htmlentities(stripslashes($_GET['game']));
                            file_put_contents("mtm_db/events/$userid", "./server set-gamemode $userid $gamename");
                            header("Location: index.php?do=manage");
                        } else {
                            echo "ERROR: " . $_GET['game'] . " not found as a game<br />";
                        }
                    } else {
                        echo "Shut down server before game configuration...";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="configure-server")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3,url=index.php?do=configure-mods' />";
                } else {
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
                    if($serverstatus == "false") {
                        // Check if each variable is set and not empty, set in configuration file if so
                        // server_name
                        if(isset($_POST['servername']) && $_POST['servername']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "server_name = " . $_POST['servername'] . "\n", FILE_APPEND);
                        }

                        // server_description
                        if(isset($_POST['serverdesc']) && $_POST['serverdesc']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "server_description = " . $_POST['serverdesc'] . "\n", FILE_APPEND);
                        }

                        // server_url
                        if(isset($_POST['servername']) && $_POST['serverurl']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "server_url = " . $_POST['serverurl'] . "\n", FILE_APPEND);
                        }

                        // motd
                        if(isset($_POST['motd']) && $_POST['motd']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "motd = " . $_POST['motd'] . "\n", FILE_APPEND);
                        }

                        // static_spawnpoint
                        if(isset($_POST['staticspawnpoint']) && $_POST['staticspawnpoint']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "static_spawnpoint = " . $_POST['staticspawnpoint'] . "\n", FILE_APPEND);
                        }

                        // enable_pvp = true
                        if(isset($_POST['enablepvp'])) {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "enable_pvp = true\n", FILE_APPEND);
                        }

                        // enable_pvp = true
                        if(isset($_POST['creative'])) {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "creative_mode = true\n", FILE_APPEND);
                        }

                        // enable_damage = true
                        if(isset($_POST['enabledamage'])) {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "enable_damage = true\n", FILE_APPEND);
                        } else {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "enable_damage = false\n", FILE_APPEND);
                        }

                        // server_announce = true
                        if(isset($_POST['serverannounce'])) {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "server_announce = true\n", FILE_APPEND);
                        }

                        // player_transfer_distance = "value"
                        if(isset($_POST['playertransferdistance']) && $_POST['playertransferdistance']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "player_transfer_distance = " . $_POST['playertransferdistance'] . "\n", FILE_APPEND);
                        }

                        // default_privs
                        if(isset($_POST['defaultprivs']) && $_POST['defaultprivs']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "default_privs = " . $_POST['defaultprivs'] . "\n", FILE_APPEND);
                        }

                        // mapgen settings
                        if(isset($_POST['mgname']) && $_POST['mgname']!="") {
                            file_put_contents("mtm_db/worlds/$userid/minetest.conf", "mg_name = " . $_POST['mgname'] . "\n", FILE_APPEND);
                        }

                        header("Location: index.php?do=manage");
                    } else {
                        echo "Shut down server before configuration...";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="configure-mods")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
                    if($serverstatus == "false") {
                        // Let them know this might take a while
                        echo "Please wait, this might take a few seconds depending on the amount of mods being enabled...";
                        // Check to see which mods where selected, and go from there!
                        chdir("mods");
                        foreach(glob("*") as $modname) {
                            // server_announce = true
                            if(isset($_POST[$modname]) && !is_dir("../mtm_db/worlds/$userid/worlds/world/worldmods/$modname")) {
                                echo "Copying $modname...";
                                chdir("..");
                                file_put_contents("mtm_db/events/$userid", "cp -a mods/$modname mtm_db/worlds/$userid/worlds/world/worldmods/$modname");
                                chdir("mods");
                                sleep(1);
                            }
                        }
                        chdir("..");
                        header("Location: index.php?do=manage");
                    } else {
                        echo "Shut down server before configuration...";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="configure-user-mods")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
                    if($serverstatus == "false") {
                        // Let them know this might take a while
                        echo "Please wait, this might take a few seconds depending on the amount of mods being enabled...";
                        // Check to see which mods where selected, and go from there!
                        chdir("mtm_db/usermods/$username");
                        foreach(glob("*") as $modname) {
                            // server_announce = true
                            if(isset($_POST[$modname])) {
                                echo "Copying $modname...";
                                chdir("../..");
                                file_put_contents("events/$userid", "cp -a mtm_db/usermods/$username/$modname mtm_db/worlds/$userid/worlds/world/worldmods/$modname");
                                chdir("usermods/$username");
                                sleep(2);
                            }
                        }

                        chdir("../../../");

                        header("Location: index.php?do=manage");
                    } else {
                        echo "Shut down server before configuration...";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

	if($do=="start") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(is_dir("mtm_db/worlds/$userid")) {
				if(!is_dir("mtm_db/worlds/$userid/bin")) {
					echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3' />";
				} else {
					$serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
					if($serverstatus == "false" || !file_exists("mtm_db/users/$userid.pid")) {
						$servertype = file_get_contents("mtm_db/users/$userid.type");
						if($servertype == "multicraft") {
							file_put_contents("mtm_db/events/$userid", "./server start-multicraft $userid");
						} else if($servertype == "minetest") {
							file_put_contents("mtm_db/events/$userid", "./server start-minetest $userid");
						}
						header("Location: index.php?do=manage");
					} else {
						echo "Server already running...";
					}
				}
			} else {
				echo "ERROR: Server not found!";
			}
		}
	}
	
	if($do=="stop") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(is_dir("mtm_db/worlds/$userid")) {
				if(!is_dir("mtm_db/worlds/$userid/bin")) {
					echo "Pending: Server is pending creation, this process shouldn't take longer than 30 seconds...";
                    echo "<meta http-equiv='refresh' content='3' />";
				} else {
					$serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
					if($serverstatus == "true") {
						file_put_contents("mtm_db/events/$userid", "./server stop $userid");
						header("Location: index.php?do=manage");
					} else {
						echo "Server already stopped...";
					}
				}
			} else {
				echo "ERROR: Server not found!";
			}
		}
	}
	
	if($do=="delete") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(is_dir("mtm_db/worlds/$userid")) {
				$serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
				if($serverstatus == "true") {
					file_put_contents("mtm_db/events/$userid", "./server del $userid");
					sleep(2);
					header("Location: index.php");
				} else {
                    file_put_contents("mtm_db/events/$userid", "./server del $userid");
                    sleep(2);
					header("Location: index.php");
				}
			} else {
				echo "ERROR: Server not found!";
			}
		}
	}
	
    if($do=="info-debug") {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 3 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    echo $username . "'s Server<br /> Server status: ";
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.status");
                    echo $serverstatus;
                    echo "<br /><a href='index.php?do=reset-config' class='button'>Reset minetest.conf</a> &nbsp;";
                    echo " <a href='index.php?do=del-logfile' class='button'>Reset logfile</a>\n";
                    echo "<h3>Server information</h3>";
                    echo "<h4>minetest.conf</h4>";
                    $userserverconfig = file_get_contents("mtm_db/worlds/$userid/minetest.conf");
                    echo "<code><pre>$userserverconfig</pre></code>";

                    echo "<h4>server log</h4>";
                    $userserverdebug = file_get_contents("mtm_db/users/$userid.slog");
                    echo "<code><pre>$userserverdebug</pre></code>";
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

	if($do=="manage") {
		if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
			include("mtm_db/users/$username.php");
			if(is_dir("mtm_db/worlds/$userid")) {
				if(!is_dir("mtm_db/worlds/$userid/bin")) {
					echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
					// Refresh the page every 3 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='1' />";
				} else {

                    // Check if usermods folder exists, create if not!
                    // For users that created their accounts before update.
                    if(!is_dir("mtm_db/usermods/$username")) {
                        mkdir("mtm_db/usermods/$username");
                    }

					echo $username . "'s Server<br /> Server status: ";
					$serverstatus = file_get_contents("mtm_db/users/$userid.pid.status");
					echo $serverstatus;
					echo "<br /><br /><a href='index.php?do=start' class='button'>Start</a>&nbsp;";
                    echo "<a href='index.php?do=stop' class='button'>Stop</a>&nbsp;<a href='index.php?do=delete' class='button'>Delete</a><br />";
                    echo "<a href='index.php?do=settings' class='button'>Server Settings</a>&nbsp;<a href='index.php?do=mods' class='button'>Mod Settings</a>&nbsp;";
                    echo "<a href='index.php?do=info-debug' class='button'>Server Information</a>";
					echo "<br /><br />";
					echo "<b>Connection information:</b><br />";
					echo "<table><tr><td>IP/Port:</td><td>" . $defaultip . "/" . $portrange . $userid . "</td></tr>";
					echo "<tr><td>Admin: </td><td>$username</td></tr>";
                    echo "</table>\n";

                    if(is_dir("mtm_db/worlds/$userid/worlds/world/worldmods")) {
                        echo "<h4>mods enabled</h4>";
                        echo "<ol>";
                        chdir("mtm_db/worlds/$userid/worlds/world/worldmods");
                        foreach(glob("*") as $mods) {
                            echo "<li>$mods</li>";
                        }
                        echo "</ol>";
				    }
                    echo "<meta http-equiv='refresh' content='5' />";
                }
			} else {
				echo "ERROR: Server not found!";
			}
		}
	}

    if($do=="settings")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='5' />";
                } else {
                    echo $username . "'s Server<br /> Server status: ";
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.status");
                    echo $serverstatus;
                    echo "<br />";
                    echo "<h3>Configure minetest.conf</h3>";
                    settingsForm();
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="upload-modzip")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    // Lets checkout what's being uploaded
                    if(isset($_POST['upload-btn'])) {
                        $filename = basename($_FILES['file']['name']);
                        $filetype = $_FILES['file']['type'];
                        $filesize = $_FILES['file']['size'];
                        if($filesize > $max_modzip_size) {
                            echo "Error on mod upload, file too big!";
                        } else if (strtolower(pathinfo($filename,PATHINFO_EXTENSION))!=$allowed_file_extension) {
                            echo "Error on mod upload, ZIP archives only!";
                        } else if (($_FILES["file"]["type"] == "application/zip")
                               || ($_FILES["file"]["type"] == "application/octet-stream")) {
                            // Looking good!
                            if($_FILES['file']['error'] > 0) {
                                echo "Unknown error code: " . $_FILES['file']['error'];
                            } else {
                                move_uploaded_file($_FILES['file']['tmp_name'], "mtm_db/usermods/$username/tmpmod.zip");
                                file_put_contents("mtm_db/events/$userid", "unzip mtm_db/usermods/$username/tmpmod.zip -d mtm_db/usermods/$username/");
                                sleep(4);
                                // Delete the mod zip after extraction
                                unlink("mtm_db/usermods/$username/tmpmod.zip");
                                header("Location: index.php?do=mods");
                            }
                        } else {
                            echo "Error on mod upload, archive mimetype was not of a ZIP archive.";
                        }
                    } else {
                        echo "Upload button causing some issues?";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="mods")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    echo $username . "'s Server<br /> Server status: ";
                    $serverstatus = file_get_contents("mtm_db/users/$userid.pid.status");
                    echo $serverstatus;
                    echo "<br /><a href='index.php?do=reset-mods' class='button'>Reset mods</a>\n";
                    echo "<h3>Change default game</h3>";
                    chdir("games");
                    foreach(glob("*") as $gamemode) {
                        echo "<a href='index.php?do=configure-game&game=$gamemode' class='button'>$gamemode</a> ";
                    }
                    chdir("..");

                    echo "<h3>Enable mods from local repository</h3>";
                    modsForm();

                    // Disable user uploads of zip files when given to general public.
                    if($reg_token_required == "true") {

                        echo "<h3>Enable user available mods</h3>";
                        // In case someone fucks there shit up
                        echo "<a href='index.php?do=reset-user-mods' class='button'>Delete user mods</a><br />";
                        userModsForm($username);

                        echo "<h3>Personal mod upload</h3>";
                        modUploadForm();

                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="reset-mods")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    if(is_dir("mtm_db/worlds/$userid/worlds/world/worldmods")) {
                        $serverstatus = file_get_contents("mtm_db/users/$userid.pid.statuscode");
                        if($serverstatus == "false") {
                            file_put_contents("mtm_db/events/$userid", "rm -r mtm_db/worlds/$userid/worlds/world/worldmods/*");
                            sleep(1);
                            header("Location: index.php?do=manage");
                        } else {
                            echo "Error: please shut down your server before deleting world mods!";
                        }
                    } else {
                        echo "Error: mods directory for your world doesn't exit!";
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="reset-user-mods")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds...";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    if(is_dir("mtm_db/usermods/$username")) {
                        file_put_contents("mtm_db/events/$userid", "rm -r mtm_db/usermods/$username/*");
                        sleep(2);
                        header("Location: index.php?do=manage");
                    }
                }
            } else {
                echo "ERROR: Server not found!";
            }
        }
    }

    if($do=="reset-config")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Please wait: Server is being created, this process shouldn't take longer than 30 seconds... If you haven't created a server yet, do so before trying to reset a configuration file.";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='5' />";
                } else {
                    // Lets setup a default configuration script
                    $config_contents = "port = 30" . $userid . "\n";
                    $config_contents .= "name = " . $username . "\n";
                    $config_contents .= "max_users = $max_slot_count\n";
                    $config_contents .= "default_game = minetest_game\n";
                    $config_contents .= "default_privs = shout, interact\n";
                    $config_contents .= "secure.trusted_mods = irc\n";
                    $config_contents .= "server_address = $defaultip\n";
                    $config_contents .= "irc.server = $default_irc_server\n";
                    $config_contents .= "irc.port = $default_irc_port\n";
                    $config_contents .= "irc.nick = MT" . $portrange . $userid . "\n";
                    $config_contents .= "irc.channel = #$username\n";
                    file_put_contents("mtm_db/worlds/$userid/minetest.conf", $config_contents);
                    header("Location: index.php?do=manage");
                }
            } else {

            }
        }
    }

    if($do=="del-logfile")
    {
        if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass'])) { loginForm(); } else {
            include("mtm_db/users/$username.php");
            if(is_dir("mtm_db/worlds/$userid")) {
                if(!is_dir("mtm_db/worlds/$userid/bin")) {
                    echo "Server doesn't exist... unable to remove debug.txt";
                    // Refresh the page every 5 seconds for updates on the VM status.
                    echo "<meta http-equiv='refresh' content='3' />";
                } else {
                    // Lets setup a default configuration script
                    if(!file_exists("mtm_db/users/$userid.slog")) {
                        echo "ERROR: debug.txt doesn't exist...";
                    } else {
                        unlink("mtm_db/users/$userid.slog");
                        header("Location: index.php?do=manage");
                    }
                }
            } else {
                echo "ERROR: Somethings not right, user directory not found!";
            }
        }
    }

	if($do=="about")
	{
		echo "<h2>About</h2>";
		echo "<p>" . $desc;
        
        $guestabout = file_get_contents("text/about.txt");
        echo $guestabout;
		echo "<br />If you enjoy our services, please consider donating!";
	}

	if($do=="login")
	{
		$username = stripslashes(htmlentities($_POST['username']));
        if($username == "admin") {
            if($admin_passwd == stripslashes(htmlentities($_POST['password']))) {
                $pass = sha1(md5($admin_passwd));
                $user = $username;
                $_SESSION['mtm-user'] = $user;
                $_SESSION['mtm-pass'] = $pass;
                header("Location: index.php");
            } else {
                echo "Wrong administrator password!";
            }
        } else if(file_exists("mtm_db/users/$username.php")) {
			include_once("mtm_db/users/$username.php");
			if($user_password == sha1(md5($_POST['password']))) {
				$pass = $user_password;
				$user = $username;
				$_SESSION['mtm-user'] = $user;
				$_SESSION['mtm-pass'] = $pass;
				header("Location: index.php");
			} else {
				echo "Wrong password!";
			}
		} else {
			echo "User $username not found!";
		}
	}

    if($do=="admin-start-all") {
        if($username=="admin" && $_SESSION['mtm-pass']==sha1(md5($admin_passwd))) {
            // To be continued!
            chdir("mtm_db/users");
            echo "Starting servers...";
            foreach(glob("*.php") as $user_account_file) {
                include_once($user_account_file);
                $servertype = file_get_contents("$userid.type");
                $serverstatus = file_get_contents("$userid.pid.status");
                $statuscode = file_get_contents("$userid.pid.statuscode");
                if(!file_exists("$userid.pid.statuscode") || $statuscode == "false") {
                    chdir("..");
                    if($servertype == "multicraft" && is_dir("worlds/$userid/bin")) {
                        file_put_contents("events/$userid", "./server start-multicraft $userid");
                        sleep(1);
                        echo "Starting multicraft world $userid...<br />";
                    } else if($servertype == "minetest" && is_dir("worlds/$userid/bin")) {
                        file_put_contents("events/$userid", "./server start-minetest $userid");
                        sleep(1);
                        echo "Starting minetest world $userid...<br />";
                    } else {
                        echo "World not created for $userid...<br />";
                    }
                    chdir("users");
                }
            } 
        }
    }

    if($do=="admin-stop-all") {
        if($username=="admin" && $_SESSION['mtm-pass']==sha1(md5($admin_passwd))) {
            echo "Stopping servers...";
            if(!isset($userid)) { $userid = "1"; }
            file_put_contents("mtm_db/events/$userid", "./server stopall");
        }
    }

	if($do=="logout")
	{
	    $_SESSION['mtm-user'] = null;
	    $_SESSION['mtm-pass'] = null;
        header("Location: index.php?forms=login");
	}

	if($do=="register")
	{
		if($_POST['username']!="" && $_POST['password']!="" && $_POST['password-again']!="" && $_POST['fullname']!="" && isset($_POST['email']) && $_POST['email']!="") {
			if($_POST['password']==$_POST['password-again']) {
				if(!preg_match('/[^a-z0-9]/i', $_POST['username']) && $_POST['username']!="admin") {
					if(!file_exists("mtm_db/users/" . $_POST['username'] . ".php")) {
						$servercount = file_get_contents("mtm_db/users/usercount");
						if($servercount < $maxservers)
						{
							if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                                include_once("mtm_db/token.php");
                                // Enable registration tokens via config.php now!
                                if($reg_token_required == "true") {

								if(stripslashes(htmlentities($_POST['codeword'])) == $reg_token) {
									$servercount = $servercount + 1;
                                    if ($servercount < 10) {
                                        $usergenid = "00" . $servercount;
                                    } else if ($servercount < 100) {
                                        $usergenid = "0" . $servercount;
                                    } else {
                                        $usergenid = $servercount;
                                    }

                                    generateToken();

									file_put_contents("mtm_db/users/usercount", $servercount);
									file_put_contents("mtm_db/users/" . stripslashes(htmlentities($_POST['username'])) . ".php", "<?php\n\$user_handle = \"" . stripslashes(htmlentities($_POST['username'])) . "\";\n\$user_password = \"" . sha1(md5($_POST['password'])) . "\";\n \$user_email = \"" . stripslashes(htmlentities($_POST['email'])) . "\"; \$user_fullname = \"" . stripslashes(htmlentities($_POST['fullname'])) . "\"; \$userid = \"" . $usergenid . "\";\n?>");
									header("Location: index.php");
								}
								else
								{
									echo "ERROR: Registration code incorrect, please try again!";
								}
                                
                                } else { // Else we aren't using registration codes! FREE SERVERS

                                    $servercount = $servercount + 1;
                                    if ($servercount < 10) {
                                        $usergenid = "00" . $servercount;
                                    } else if ($servercount < 100) {
                                        $usergenid = "0" . $servercount;
                                    } else {
                                        $usergenid = $servercount;
                                    }

                                    file_put_contents("mtm_db/users/usercount", $servercount);
                                    file_put_contents("mtm_db/users/" . stripslashes(htmlentities($_POST['username'])) . ".php", "<?php\n\$user_handle = \"" . stripslashes(htmlentities($_POST['username'])) . "\";\n\$user_password = \"" . sha1(md5($_POST['password'])) . "\";\n \$user_email = \"" . stripslashes(htmlentities($_POST['email'])) . "\"; \$user_fullname = \"" . stripslashes(htmlentities($_POST['fullname'])) . "\"; \$userid = \"" . $usergenid . "\";\n?>");
                                    header("Location: index.php");

                                } // End registration tokens via config.php
							} 
							else
							{
								echo "ERROR: Email is invalid!";
							}
						}
						else 
						{
							echo "ERROR: Server cap reached!";
						}
					} else {
						header("Location: index.php?notify=6");
					}
				} else {
					header("Location: index.php?notify=5");
				}
			} else {
				header("Location: index.php?notify=4");
			}
		} else {
			header("Location: index.php?notify=3");
		}
	}
}
else if (!isset($_SESSION['mtm-user']) || !isset($_SESSION['mtm-pass']))
{
        header("Location: index.php?do=about");
}
else
{
    if($username!="admin") {
    	include("mtm_db/users/$username.php");
	    if(!is_dir("mtm_db/worlds/$userid"))
	    {
		    echo "<h3>Minetest server creation</h3>";
		    echo "<p>You will have the ability to create a server, and will have a consistent uptime based on server uptime, and automated server management!";
            echo "There's mods and gamepacks available to users and can be toggled on and off! Over time, more will be populated into the local repository.</p>";
            // Get home page for non-users based on users wants
            $useraboutmulticraft = file_get_contents("text/multicraft.txt");
            $useraboutminetest = file_get_contents("text/minetest.txt");
            echo "<p>";
            echo $useraboutmulticraft . "<br />";
		    echo "<div style='display:block;width:100%;text-align:center;'><a href='index.php?do=create-multicraft' class='button'>Go with MultiCraft</a></div>";
            echo "</p>";

            echo "<p>";
            echo $useraboutminetest . "<br />";
            echo "<div style='display:block;width:100%;text-align:center;'><a href='index.php?do=create-minetest' class='button'>Go with Minetest current</a></div>";
            echo "</p>";

	    }
	    else
        {
            header("Location: index.php?do=manage");
        }
    } else {
        // This is the admin panel!
        echo "<h3>Administration panel</h3>";
        if(!file_exists("mtm_db/token.php")) { generateToken(); }

        include_once("mtm_db/token.php");
        echo "<p>Current registration token: $reg_token</p>";

        echo "<h3>Server information</h3>";
        // Open system meminfo
        $fhmem = fopen('/proc/meminfo','r');
        // Open system loadavg
        $fhcpu = fopen('/proc/loadavg','r');
        // Set to 0 for population
        $memavail = 0;
        $memfree = 0;

        while ($line = fgets($fhmem)) {
            $piecesavail = array();
            $piecesfree = array();
            if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $piecesavail)) {
                $memavail = $piecesavail[1];
            }

            if (preg_match('/^MemAvailable:\s+(\d+)\skB$/', $line, $piecesfree)) {
                $memfree = $piecesfree[1];
                break;
            }
        }

        fclose($fhmem);

        echo round(($memavail/1024)) . " MB RAM found, " . round(($memfree/1024)) . " MB RAM free<br />\n";

        while ($line = fgets($fhcpu)) {
            echo "Load: " . $line;
        }

        fclose($fhcpu);

        // Admin server controls.
        echo "<br />";
        echo "<a href='index.php?do=admin-start-all' class='button'>Start All</a>";
        echo "<a href='index.php?do=admin-stop-all' class='button'>Stop All</a><br />";

        // To be continued!
        chdir("mtm_db/users");
        echo "<div id='admint'><table><tr><td>Username</td><td>Full Name</td><td>Email</td><td>Server-Type/Port</td><td>User ID</td><td>Server Stat</td></tr>";
        foreach(glob("*.php") as $user_account_file) {
            include_once($user_account_file);
            $servertype = file_get_contents("$userid.type");
            $serverstatus = file_get_contents("$userid.pid.status");
            echo "<tr><td>$user_handle</td><td>$user_fullname</td><td>$user_email</td><td>$servertype/$portrange$userid</td><td>$userid</td><td>$serverstatus</td></tr>";
        }
        echo "</table></div>";
    }
}

?>

<br /><br />
<div style="margin: auto; width: 100%; text-align: center; background-color: #555555; padding: 3px;">Powered By <a href="https://notabug.org/Pentium44/MTSM">MTSM</a> <?php echo $version; ?> <br />
</div>
</div>
</div> <!-- main contain -->
</body>
</html>
